package com.chengyu.core.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chengyu.core.dao.AssistDao;
import com.chengyu.core.domain.CommonConstant;
import com.chengyu.core.entity.CommonPage;
import com.chengyu.core.exception.CommonException;

import com.chengyu.core.exception.ServiceException;
import com.chengyu.core.model.Assist;
import com.chengyu.core.request.PageParamRequest;
import com.chengyu.core.service.AssistService;
import com.chengyu.core.utils.StringUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 援助 服务实现类
 * </p>
 *
 * @author wenlj
 * @since 2023-10-29
 */
@Service
public class AssistServiceImpl extends ServiceImpl<AssistDao, Assist> implements AssistService {

    @Autowired
    private AssistDao dao;


    /**
     * 获取列表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页参数
     * @return PageInfo
     */
    @Override
    public PageInfo<Assist> getList(Assist request, PageParamRequest pageParamRequest) {
        Page<Assist> assistPage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());



        LambdaQueryWrapper<Assist> lqw = Wrappers.lambdaQuery();



        if (ObjectUtil.isNotNull(request.getMemberId())) {
            lqw.eq(Assist::getMemberId, request.getMemberId());
        }

        if (ObjectUtil.isNotNull(request.getType())) {
            lqw.eq(Assist::getType, request.getType());
        }
        if (StrUtil.isNotBlank(request.getTitle())) {
            String title = URLUtil.decode(request.getTitle());
            lqw.like(Assist::getTitle, title);
        }
        if (StrUtil.isNotBlank(request.getAuthor())) {
            lqw.eq(Assist::getAuthor, URLUtil.decode(request.getAuthor()));
        }
        lqw.eq(Assist::getIsDel, false);
        lqw.orderByDesc(Assist::getSort).orderByDesc(Assist::getId);
        List<Assist> assistList = dao.selectList(lqw);

        List<Assist> responseList = new ArrayList<>();
        if (CollUtil.isEmpty(assistList)) {
            return CommonPage.copyPageInfo(assistPage, responseList);
        }
        for (Assist assist : assistList) {
            Assist response = new Assist();
            BeanUtils.copyProperties(assist, response);
            responseList.add(response);
        }
        return CommonPage.copyPageInfo(assistPage, responseList);
    }

//
//    @Override
//    public PageInfo<Assist> getList(String cid, PageParamRequest pageParamRequest) {
//        Page<Assist> assistPage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
//
//        LambdaQueryWrapper<Assist> lqw = Wrappers.lambdaQuery();
//
//
////        lqw.eq(Assist::getCid, cid);
//        lqw.eq(Assist::getStatus, true);
//        lqw.eq(Assist::getIsDel, false);
//        lqw.orderByDesc(Assist::getSort, Assist::getId).orderByDesc(Assist::getVisit).orderByDesc(Assist::getCreateTime);
//        List<Assist> assistList = dao.selectList(lqw);
//        if (CollUtil.isEmpty(assistList)) {
//            return CommonPage.copyPageInfo(assistPage, CollUtil.newArrayList());
//        }
//        List<Assist> responseList = assistList.stream().map(e -> {
//            Assist assistResponse = new Assist();
//            BeanUtils.copyProperties(e, assistResponse);
//            return assistResponse;
//        }).collect(Collectors.toList());
//        return CommonPage.copyPageInfo(assistPage, responseList);
//    }


    /**
     * 查询详情
     *
     * @param id Integer
     * @return AssistVo
     */
    @Override
    public Assist getVoByFront(Integer id)  {
        Assist pmsAssist = getById(id);
        if (ObjectUtil.isNull(pmsAssist) || pmsAssist.getIsDel()==1) {
            throw new CommonException("不存在");
        }
        if (pmsAssist.getStatus()==0) {
            throw new CommonException("不存在");
        }
        Assist assistResponse = new Assist();
        BeanUtils.copyProperties(pmsAssist, assistResponse);
//        if (addAssistVisit(id)) {
//            logger.error("增加阅读次数失败，id = {}", id);
//        }
        return assistResponse;
    }

    /**
     * 获取详情
     *
     * @param id id
     * @return Assist
     */
    @Override
    public Assist getDetail(Integer id) {
        Assist assist = getByIdException(id);
        Assist response = new Assist();
        BeanUtils.copyProperties(assist, response);
        return response;
    }



    /**
     * 增加浏览次数
     *
     * @param id id
     */
    private Boolean addAssistVisit(Integer id) {
        UpdateWrapper<Assist> wrapper = Wrappers.update();
        wrapper.setSql("visit = visit + 1");
        wrapper.eq("id", id);
        return update(wrapper);
    }

    /**
     * 获取移动端banner列表
     *
     * @return List<Assist>
     */
    @Override
    public List<Assist> getBannerList() {
        int assistBannerLimit = 5;
        // 根据配置控制banner的数量
//        String assistBannerLimitString = systemConfigService.getValueByKey(SysConfigConstants.assist_BANNER_LIMIT);
//        if (StrUtil.isNotBlank(assistBannerLimitString)) {
//            assistBannerLimit = Integer.parseInt(assistBannerLimitString);
//        }
        LambdaQueryWrapper<Assist> lqw = Wrappers.lambdaQuery();
        lqw.select(Assist::getId, Assist::getCover, Assist::getTitle);
        lqw.eq(Assist::getIsBanner, true);
        lqw.eq(Assist::getStatus, true);
        lqw.eq(Assist::getIsDel, false);
        lqw.orderByDesc(Assist::getSort, Assist::getId);
        lqw.last(" limit " + assistBannerLimit);
        return dao.selectList(lqw);
    }

    /**
     * 获取移动端热门列表
     *
     * @return List<Assist>
     */
    @Override
    public List<Assist> getHotList() {
        LambdaQueryWrapper<Assist> lqw = Wrappers.lambdaQuery();
        lqw.select(Assist::getId, Assist::getCover, Assist::getTitle, Assist::getCreateTime);
        lqw.eq(Assist::getIsHot, true);
        lqw.eq(Assist::getStatus, true);
        lqw.eq(Assist::getIsDel, false);
        lqw.orderByDesc(Assist::getSort, Assist::getId);
        lqw.last(" limit 20");
        List<Assist> assistList = dao.selectList(lqw);
        if (CollUtil.isEmpty(assistList)) {
            return CollUtil.newArrayList();
        }
        return assistList.stream().map(e -> {
            Assist assistResponse = new Assist();
            BeanUtils.copyProperties(e, assistResponse);
            return assistResponse;
        }).collect(Collectors.toList());
    }

    /**
     * 新增
     *
     * @param request 新增参数
     * @return Boolean
     */
    @Override
    public Boolean create(Assist request) {
        Assist assist = new Assist();
        BeanUtils.copyProperties(request, assist);
        assist.setId(null);
//        String cdnUrl = systemAttachmentService.getCdnUrl();
//        assist.setCover(systemAttachmentService.clearPrefix(assist.getCover(), cdnUrl));
//        assist.setContent(systemAttachmentService.clearPrefix(assist.getContent(), cdnUrl));
        assist.setVisit(0L);
        return save(assist);
    }


    /**
     * 修改
     *
     * @param request 修改参数
     */
    @Override
    public Boolean updateAssist(Assist request) {
        if (ObjectUtil.isNull(request.getId())) {
            throw new CommonException("ID不能为空");
        }
        Assist  assist  =  getByIdException(request.getId());
        if(assist.getMemberId().equals(request.getMemberId())){

//        Assist assist = new Assist();
            BeanUtils.copyProperties(request, assist);
//        String cdnUrl = systemAttachmentService.getCdnUrl();
//        assist.setCover(systemAttachmentService.clearPrefix(assist.getCover(), cdnUrl));
//        assist.setContent(systemAttachmentService.clearPrefix(assist.getContent(), cdnUrl));
            return updateById(assist);
        }else{
            throw new CommonException("操作错误");
        }
    }




    /**
     * 修改
     *
     * @param request 修改参数
     */
    @Override
    public Boolean pushAssist(Assist request) {
//        if (ObjectUtil.isNull(request.getId())) {
//            throw new CommonException("ID不能为空");
//        }
//        getByIdException(request.getId());
//        Assist assist = new Assist();
//        BeanUtils.copyProperties(request, assist);


        String[] imagesdList = request.getImages().split(CommonConstant.DH_REGEX);

        if(imagesdList!=null) request.setCover(imagesdList[0]);

        if(request.getId() == null){
               return  create(request);
        }else{
            return updateAssist(request);
        }


    }



    /**
     * 删除
     *
     * @param id id
     * @return Boolean
     */
    @Override
    public Boolean deleteById(Integer id) {
        Assist assist = getByIdException(id);
        assist.setIsDel(1);
        return updateById(assist);
    }


    @Override
    public Boolean deleteByIdWithMemberId(Integer id,Integer memberId) {
        Assist assist = getByIdMemberIdException(id,memberId);

        System.out.println(id);
        System.out.println(memberId);


        if (memberId.equals(0) ) {
            throw new CommonException("操作错误1！！！！！！");
        }

        if (!memberId.equals(assist.getMemberId())) {
            throw new CommonException("操作错误2！！！！！！");
        }



        assist.setIsDel(1);
        return updateById(assist);
    }

    private Assist getByIdException(Integer id) {
        Assist assist = getById(id);
        if (ObjectUtil.isNull(assist) || assist.getIsDel()==1) {
            throw new CommonException("不存在");
        }
        return assist;
    }

    private Assist getByIdMemberIdException(Integer id,Integer memberId) {
        Assist assist = getById(id);

        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("member_id", memberId);
        List<Assist> list = dao.selectByMap(map);

        list.forEach(System.out::println);



        if (ObjectUtil.isNull(assist) || assist.getIsDel()==1) {
            throw new CommonException("不存在");
        }
        return assist;
    }



    /**
     * 是否使用分类
     *
     * @param categoryId 分类ID
     * @return Boolean
     */
    @Override
    public Boolean isUseCategory(Integer categoryId) {
        LambdaQueryWrapper<Assist> lqw = Wrappers.lambdaQuery();
        lqw.eq(Assist::getType, categoryId);
        lqw.eq(Assist::getIsDel, false);
        lqw.eq(Assist::getIsDel, false);
        lqw.last(" limit 1");
        Assist assist = dao.selectOne(lqw);
        return ObjectUtil.isNotNull(assist);
    }

    /**
     * 获取首页新闻头条
     */
    @Override
    public List<Assist> getIndexHeadline() {
        LambdaQueryWrapper<Assist> lqw = Wrappers.lambdaQuery();
        lqw.select(Assist::getId, Assist::getTitle);
        lqw.eq(Assist::getIsHot, true);
        lqw.eq(Assist::getStatus, true);
        lqw.eq(Assist::getIsDel, false);
        lqw.orderByDesc(Assist::getSort);
        lqw.last(" limit 10");
        return dao.selectList(lqw);
    }

    /**
     * 开关
     * @param id id
     * @return Boolean
     */
    @Override
    public Boolean assistSwitch(Integer id) {
        Assist assist = getByIdException(id);
        assist.setStatus(assist.getStatus()==1?0:1);
        return updateById(assist);
    }
}
